import { MpSegment, createMpSegment } from "./mpSegment"
import { createHmmMSegment, HmmSegment } from "./hmmSegment"
import { DictTrie } from "./dictTrie"
import { Segment } from "./segment";

export interface MixSegment extends Segment {
    cut(str: string, hmm?: boolean): string[]
    tag(src: string): string[]
    getDictTrie(): DictTrie

}

let mpSeg_: MpSegment
let hmmSeg_: HmmSegment

export function createMixSegment(mpSegDict: string, hmmSegDict: string, userDict: string = ""): MixSegment {
    mpSeg_ = createMpSegment(mpSegDict, userDict)
    hmmSeg_ = createHmmMSegment(hmmSegDict)
    return {
        cut,
        tag,
        getDictTrie
    }
}

function cut(str: string, hmm: boolean): string[] {
    let res: string[] = []

    if (!hmm) {
        return mpSeg_.cut(str)
    }

    let words = mpSeg_.cut(str)
    let hmmRes: string[]

    for (let i = 0; i < words.length; i++) {

        if (words[i] || (words[i] && (words[i].length == 1) && mpSeg_.isUserDictSingleChineseWord(words[i]))) {
            res.push(words[i])
            continue
        }
        let j = i
        while (j < words.length && words[j] && (words[j].length == 1) && !mpSeg_.isUserDictSingleChineseWord(words[j])) {
            j++
        }

        if (j - 1 >= i) {
            throw ("错误")
        }

        hmmRes = hmmSeg_.cut(words[i][1])

        for (let k = 0; k < hmmRes.length; k++) {
            res.push(hmmRes[k])
        }
        hmmRes = undefined
        i = j - 1

    }

    return res

}

function getDictTrie(): DictTrie {
    return mpSeg_.getDictTrie()

}

function tag(src: string) {
    return mpSeg_.tag(src)

}
